//
//  SIEmotionManager.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/10.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

/// 表情管理器
class SIEmotionManager {

    /// 单例
    static let shared = SIEmotionManager()
    
    lazy var packages = [SIEmoticonPackage]()
    
    lazy var bundle: Bundle = {
        let path = Bundle.main.pathForResource("HMEmoticon.bundle", ofType: nil)
        
        return Bundle(path: path!)!
        
    }()
    
    /// 私有构造函数,保证外部只能通过单例访问本类
    private init() {
        
        loadPackages()
    }
    
    /// 添加最近使用的表情
    ///
    func recentEmoticon(em: SIEmoticon) {
        
        em.times += 1
        
        if !packages[0].emoticons.contains(em) {
            
            packages[0].emoticons.append(em)
        }
        
        packages[0].emoticons.sort { (em1, em2) -> Bool in
            
            return em1.times > em2.times
        }
        
        if packages[0].emoticons.count > 20 {
            
            packages[0].emoticons.removeSubrange(20..<packages[0].emoticons.count)
        }
        
    }

}

extension SIEmotionManager {
    
    /// 生成属性文本
    /// 要按照匹配的结果倒序替换属性文本
    func emoticonString(string: String, font: UIFont) -> AttributedString {
        
        let attrString = NSMutableAttributedString(string: string)
        
        let pattern = "\\[.*?\\]"
        
        guard let regx = try? RegularExpression(pattern: pattern, options: []) else {
            
            return attrString
        }
        
        let matches = regx.matches(in: string, options: [], range: NSRange(location: 0, length: attrString.length))
        
        for m in matches.reversed() {
            
            let r = m.range(at: 0)
            
            let subStr = (attrString.string as NSString).substring(with: r)
            
            if let em = SIEmotionManager.shared.findEmoticon(string: subStr) {
                
                attrString.replaceCharacters(in: r, with: em.imageText(font: font))
            }
        }
        
        attrString.addAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.darkGray()], range: NSRange(location: 0, length: attrString.length))
        
        return attrString
        
    }
    
    /// 根据字符串查找对应的表情
    func findEmoticon(string: String) -> SIEmoticon? {
        for p in packages {
            
            let result = p.emoticons.filter({ (em) -> Bool in
                return em.chs == string
            })
            if result.count == 1 {
                return result[0]
            }
        }
        
        return nil
    }
    
}

private extension SIEmotionManager {
    
    /// 加载表情包数据
    func loadPackages() {
        
        guard let path = Bundle.main.pathForResource("HMEmoticon.bundle", ofType: nil),
            bundle = Bundle(path: path),
            plistPath = bundle.pathForResource("emoticons.plist", ofType: nil),
            array = NSArray(contentsOfFile: plistPath) as? [[String: String]],
            models = NSArray.yy_modelArray(with: SIEmoticonPackage.self, json: array) as? [SIEmoticonPackage]
            else {
                return
        }
        
        packages += models
    }
    
    
    
}
